 <template>
    <div style="display: block;background: white;">
    <el-row>
      <el-col  :span="8">
        <el-calendar v-model="value" style="color: #2c3e50;" >
        <template
          slot="dateCell"
          slot-scope="{date, data}"  @click="testclick">
          <p :class="data.isSelected ? 'is-selected' : ''"  @click="testclick">
            {{ data.day.split('-').slice(1).join('-') }} {{monthdays.includes(data.day)? '✔️' : ''}}
          </p>
        </template>
        </el-calendar>
      </el-col>
      <el-col  :span="5" style="color: #2c3e50; margin-top:30px;">
        <el-timeline >
          <el-timeline-item
              v-for="(activity, index) in activities"
              :key="index"
              :timestamp="activity.timestamp">
            {{activity.content}}   {{ getTypeName(parseInt(activity.type))}}
          </el-timeline-item>
        </el-timeline>
      </el-col>
      <el-col :span="10" style="color: #2c3e50;margin-top:30px;">
        <el-time-select
            placeholder="起始时间"
            v-model="startTime"
            :picker-options="{
              start: '07:00',
              step: '00:10',
              end: '18:30'
            }" style=" width:100px;">
        </el-time-select>
        <el-time-select
            placeholder="结束时间"
            v-model="endTime"
            :picker-options="{
              start: '07:00',
              step: '00:10',
              end: '18:30',
              minTime: startTime
            }"  style="margin-left: 5px; width:100px;">
        </el-time-select>
        <el-select v-model="selectType" placeholder="计划类型" style="margin-left: 10px;width: 120px;">
          <el-option
              v-for="item in types"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
        <el-button  style="margin-left: 5px;" @click="this.addPlan">新增计划</el-button>
        <el-input
            type="textarea"
            :rows="10"
            placeholder="请输入内容"
            v-model="plan"
            style="margin-left: 5px; margin-top: 30px; "
        >
        </el-input>
        <p style="margin-top: 200px; font-size: 20px;">今日已计划 {{this.planhours}} 小时 {{this.planminutes}} 分钟,{{this.activities.length - 1}} 个计划</p>
      </el-col>
    </el-row>
    </div>
</template>

<script>
    import axios from '@/api/ajax.js'
    import utils from '@/util/times.js'

    import  Table from 'element-ui/lib/table';
    import  TableColumn from 'element-ui/lib/table-column';
    import Vue from "vue/dist/vue.js";
    import Pagination from 'element-ui/lib/pagination';
    import Message from 'element-ui/lib/message'
    import Drawer from 'element-ui/lib/drawer'
    import MessageBox from 'element-ui/lib/message-box'
    Vue.use(Drawer);
    Vue.use(Table);
    Vue.use(TableColumn);
    Vue.use(Pagination);

    export default {
      name: "planManager",
      computed:{

      },
      data:()=>{
            return{
              date: new Date,
              data:{},
              value: new Date(),
              activities: [
              ],
              endTime:"18:30",
              startTime :"07:00",
              plan:"",
              monthdays: [],
              planhours : 0,
              planminutes : 0,
              types: [],
              selectType:""

            }
        },
        methods: {
          getTypeName(typeid){
            if(this.types[typeid] != undefined)
              return "[" + this.types[typeid].label + "]";
            else
              return ""
          },
          dateFormat(fmt, date) {
            let ret;
            const opt = {
                "Y+": date.getFullYear().toString(),        // 年
                "m+": (date.getMonth() + 1).toString(),     // 月
                "d+": date.getDate().toString(),            // 日
                "H+": date.getHours().toString(),           // 时
                "M+": date.getMinutes().toString(),         // 分
                "S+": date.getSeconds().toString()          // 秒
                // 有其他格式化字符需求可以继续添加，必须转化成字符串
            };
            for (let k in opt) {
                ret = new RegExp("(" + k + ")").exec(fmt);
                if (ret) {
                    fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
                };
            };
            return fmt;
          },
          getMonthPlans(monthdate){
              console.log("shit3",monthdate)
              let date = this.dateFormat("YYYY-mm-dd HH:MM", monthdate)
              console.log("shit4",date)

              axios.post('/plan_days', {
                    date: date
                }).then(response => {
                    if (response.data.Status === 0) {

                      this.monthdays = []
                      for (let i = 0;i < response.data.Data.length;i ++){
                          this.monthdays.push(response.data.Data[i].date)
                      }
                    }
                }).catch(reason => {
                    Message.error("网络错误:" + reason);
                });
          },
          testclick(t){
            this.timer = setTimeout(()=>{
              this.getPlans(this.dateFormat("YYYY-mm-dd", this.value))
              }, 300);
              console.log(t)
          },
          timeAfter(t1, t2){
            let hour1 = t1.split(":")
            let hour2 = t2.split(":")

            if(parseInt(hour1[0]) > parseInt(hour2[0])){
              return true
            }else if(parseInt(hour1[0]) === parseInt(hour2[0])){
              if(parseInt(hour1[1]) > parseInt(hour2[1])){
                return true
              }else{
                return  false
              }
            }else {
              return  false
            }
          },
          addPlan(){
            if(!this.timeAfter(this.endTime,this.startTime)){
                Message.error("开始时间必须小于结束时间")
                return
            }
            if(this.plan == ""){
                Message.error("请输入内容")
                return
            }
            if(this.selectType === ""){
              Message.error("请选择计划类型")
              return
            }
            for (let i = 0;i < this.activities.length; i ++){

              if((this.timeAfter(this.activities[i].startTime,this.startTime) != this.timeAfter(this.activities[i].timestamp, this.startTime))){
                Message.error("时间和 " +  this.activities[i]['content'] + "  冲突1");
                return;
              }

              if((this.timeAfter(this.activities[i].startTime,this.endTime) != this.timeAfter(this.activities[i].timestamp, this.endTime))){
                Message.error("时间和 " +  this.activities[i]['content'] + "  冲突2");
                return;
              }

              if((this.timeAfter(this.startTime,this.activities[i].startTime) != this.timeAfter(this.startTime,this.activities[i].timestamp))){
                Message.error("时间和 " +  this.activities[i]['content'] + "  冲突3");
                return;
              }

              if((this.timeAfter(this.endTime,this.activities[i].startTime) != this.timeAfter(this.endTime,this.activities[i].timestamp))){
                Message.error("时间和 " +  this.activities[i]['content'] + "  冲突4");
                return;
              }
              if((!this.timeAfter(this.startTime,this.activities[i].startTime)) && this.timeAfter(this.endTime,this.activities[i].timestamp)){
                Message.error("时间和 " +  this.activities[i]['content'] + "  冲突5");
                return;
              }
              if(!this.timeAfter(this.endTime,this.activities[i].startTime) && this.timeAfter(this.endTime,this.activities[i].timestamp)){
                Message.error("时间和 " +  this.activities[i]['content'] + "  冲突6");
                return;
              }
            }
            axios.put('/plan', {
                  date: this.dateFormat("YYYY-mm-dd", this.value),
                  content:this.plan,
                  start_time: this.dateFormat("YYYY-mm-dd", this.value) + " " + this.startTime + ":00",
                  end_time: this.dateFormat("YYYY-mm-dd", this.value) + " " + this.endTime + ":00",
                  type:this.selectType
              }).then(response => {
                  if (response.data.Status === 0) {
                    this.activities.push({'content':this.plan,'timestamp':this.endTime,'startTime':this.startTime})
                    Message.success("添加计划:  " + this.plan + " 成功");
                  }
              }).catch(reason => {
                  Message.error("网络错误:" + reason);
              });
          },
          calcMinutes(t1,t2){
            let tmp1 = t1.split(":")
            let tmp2 = t2.split(":")

            let hour1 = parseInt(tmp1[0])
            let hour2 = parseInt(tmp2[0])
            let minute1 = parseInt(tmp1[1])
            let minute2 = parseInt(tmp1[1])

            let minute1all = hour1 * 60 + minute1
            let minute2all = hour2 * 60 + minute2

            return minute1all - minute2all
          },
          getPlayType(){
            axios.get('/plan_types').then(response => {
              if (response.data.Status === 0) {
                for(let i = 0;i < response.data.Data.length; i ++){
                  this.types.push({
                    value: response.data.Data[i].id,
                    label: response.data.Data[i].type_name
                  })
                }
              }
            }).catch(reason => {
              Message.error("网络错误:" + reason);
            });
          },
          getPlans(date){
              this.activities = [{
                    content: '起床',
                    timestamp: '07:30',
                    startTime:'07:20',
                  }
                  ];
              axios.post('/get_plans', {
                  date: this.dateFormat("YYYY-mm-dd", this.value),
              }).then(response => {
                let minutes = 0;
                if (response.data.Status === 0) {
                    for (let i = 0;i < response.data.Data.length;i ++){
                        response.data.Data[i].startTime = this.dateFormat("HH:MM", new Date(response.data.Data[i].start_time))
                        response.data.Data[i].timestamp = this.dateFormat("HH:MM", new Date(response.data.Data[i].end_time))
                        this.activities.push(response.data.Data[i])
                        minutes += this.calcMinutes(response.data.Data[i].timestamp,response.data.Data[i].startTime)
                    }
                    this.planhours = minutes / 60
                    this.planminutes = minutes % 60
                }
              }).catch(reason => {
                  Message.error("网络错误:" + reason);
              });
          }
        },
        created(){
          this.getPlayType()
        },
        mounted() {
            this.$nextTick(() => {
                // 点击前一个月
                let prevBtn = document.querySelector(
                    '.el-calendar__button-group .el-button-group>button:nth-child(1)');
                prevBtn.addEventListener('click', () => {
                    this.getPlans(this.dateFormat("YYYY-mm-dd",new Date(this.value)));
                    this.getMonthPlans(new Date(this.value));
                })

            })
            this.$nextTick(() => {
                  // 点击后一个月
                  let prevBtn = document.querySelector(
                      '.el-calendar__button-group .el-button-group>button:last-child');
                  prevBtn.addEventListener('click', () => {
                    this.getPlans(this.dateFormat("YYYY-mm-dd",new Date(this.value)));
                    this.getMonthPlans(new Date(this.value));
                  })
              })
            this.getPlans(this.dateFormat("YYYY-mm-dd", new Date));
            this.getMonthPlans(new Date);
        },
        beforeCreate() {
        }
    }
</script>
<style scoped>
  .is-selected {
    color: #1989FA;
  }
</style>
